<template>
  <div class="category-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>题目分类管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="showAddDialog">添加分类</el-button>
          </div>
        </div>
      </template>

      <!-- 筛选区域 -->
      <div class="filter-container">
       <h3>分类列表</h3>
      </div>

      <!-- 分类表格 -->
      <el-table
        :data="tableData"
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column label="颜色" width="80" align="center">
          <template #default="{ row }">
            <div class="color-block" :style="{ backgroundColor: row.color }"></div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="分类名称" min-width="120" />
        <el-table-column prop="description" label="描述" min-width="180" />
        <el-table-column prop="questionCount" label="题目数量" width="100" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="120" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">
              <el-icon color="black"><Edit /></el-icon>
            </el-button>
            <el-button type="text" size="small" @click="handleDelete(row)">
              <el-icon color="red"><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="listQuery.page"
          v-model:page-size="listQuery.pageSize"
          :total="total"
          layout="total, prev, pager, next"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '添加题目分类' : '编辑题目分类'"
      width="500px"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类描述">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="categoryForm.status"
            :active-value="0"
            :inactive-value="0"
            active-text="启用"
            inactive-text="停用"
            >
            <el-option label="启动" />
            <el-option label="停用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCategory">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import '@/mockjs/ljl/category.ts'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getCategoryList, addCategory,deleteCategory } from '@/api/ljl/category.ts'
import type { ICategory, ICategoryParams, IAddCategoryParams } from '@/types/category'

// 表格数据
const tableData = ref<ICategory[]>([])
const total = ref(0)

// 查询参数
const listQuery = reactive<ICategoryParams>({
  page: 3,
  pageSize: 8,
  name: '',
  status: undefined
})

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref<'create' | 'edit'>('create')
const categoryFormRef = ref<FormInstance>()
const categoryForm = reactive<IAddCategoryParams>({
  name: '',
  description: '',
  status: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 获取分类列表
const fetchData = async () => {
    const res:any = await getCategoryList(listQuery)
    console.log('11111',res)
    tableData.value = res.list
    listQuery.page = res.list.page
    total.value = res.list.length
}


// 分页
//分页每页总条数发生变化
const handleSizeChange = (pageSize:number) => {
  listQuery.pageSize = pageSize
  fetchData()
}
//分页页码发生变化
const handleCurrentChange = (page:number) => {
  listQuery.page = page
  fetchData()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogType.value = 'create'
  resetCategoryForm()
  dialogVisible.value = true
}

// 重置表单
const resetCategoryForm = () => {
  categoryFormRef.value?.resetFields()
  Object.assign(categoryForm, {
    name: '',
    description: '',
    status: 1
  })
}

// 确认保存分类
const confirmCategory = async () => {
  try {
    await categoryFormRef.value?.validate()
    
    if (dialogType.value === 'create') {
      await addCategory(categoryForm)
      ElMessage.success('添加成功')
    } else {
      // 编辑逻辑
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('保存失败:', error)
  }
}

// 编辑分类
const handleEdit = (row: ICategory) => {
  dialogType.value = 'edit'
  Object.assign(categoryForm, {
    name: row.name,
    description: row.description,
    status: row.status
  })
  dialogVisible.value = true
}

// 删除分类
const handleDelete = (row: ICategory) => {
  ElMessageBox.confirm('确定要删除该分类吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际项目中调用删除API
    deleteCategory(row.id)
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {
    // 取消删除
  })
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.category-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-item {
  margin-right: 10px;
}

.color-block {
  width: 20px;
  height: 20px;
  margin: 0 auto;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>